package com.qianshui.co.medical.server;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.qianshui.co.medical.common.BuildResult;
import com.qianshui.co.medical.common.CommonJson;
import com.qianshui.co.medical.common.DateFormater;
import com.qianshui.co.medical.common.IDOperation;
import com.qianshui.co.medical.db.DaoFactory;
import com.qianshui.co.medical.db.Forum;
import com.qianshui.co.medical.db.ForumView;
import com.qianshui.co.medical.db.NormalAnswer;
import com.qianshui.co.medical.db.NormalAnswerView;
import com.qianshui.co.medical.db.PrivateAnswer;
import com.qianshui.co.medical.db.PublicQuestionView;
import com.qianshui.co.medical.db.Question;

@Path("ForumUtilService")
public class ForumUtilService {

	//分页查询论坛，view
	@GET
	@Path("queryForumView")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryForumView(@QueryParam("Page") String page, 
			                     @QueryParam("Number") String number,
			                     @QueryParam("userID") String userID)
			throws UnsupportedEncodingException {
		try {
			int start=Integer.parseInt(page)*Integer.parseInt(number);
			String sql="select * from forum_view where userid='"+userID+"' ORDER BY createdate DESC LIMIT "+ start +"," + number;
			List<ForumView> forum=DaoFactory.getInstance().getForumView_dao().query(sql);
            if (forum != null && forum.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, forum);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//增加新的话题，返回id
	@GET
	@Path("addForumTopic")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String addForumTopic(@QueryParam("json") String json)
			throws UnsupportedEncodingException {
		try {
			if (json != null && !json.equals("")) {
				json = URLDecoder.decode(json);
				Forum f = (Forum) CommonJson.Json2Obj(json, Forum.class);
				if (f != null) {
					f.setId(IDOperation.getClassID(Forum.class.getName()));
					f.setAnswercount(0);
					f.setCreatedate(DateFormater.getTimestampByString(DateFormater.formatLongDateTime(new Date())) );
				}

				if (DaoFactory.getInstance().getForum_dao().save(f)) {
					return BuildResult.getResult(BuildResult.Success, f.getId());
				}
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return BuildResult.getResult(BuildResult.failed, "提问失败");
	}
	
	//查询最热话题，view
	@GET
	@Path("queryHotForumView")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryHotForumView(@QueryParam("Page") String page, 
			                     @QueryParam("Number") String number)
			throws UnsupportedEncodingException {
		try {
			int start=Integer.parseInt(page)*Integer.parseInt(number);
			String sql="select * from forum_view ORDER BY answercount DESC LIMIT "+ start +"," + number;
			List<ForumView> forum=DaoFactory.getInstance().getForumView_dao().query(sql);
            if (forum != null && forum.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, forum);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//参与话题，view
	@GET
	@Path("queryPartiForumView")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryPartiForumView(@QueryParam("Page") String page, 
			                     @QueryParam("Number") String number,
			                     @QueryParam("userID") String userID)
			throws UnsupportedEncodingException {
		try {
			int start=Integer.parseInt(page)*Integer.parseInt(number);
			//String sql="select * from forum_view where id in (select questionid from normal_answer where userid= '"+userID+"' )  LIMIT "+ start +"," + number;
			String sql="select DISTINCT f.* from forum_view f inner join normal_answer n on f.id=n.questionid and n.userid='"+userID+"' LIMIT "+ start +"," + number;
			List<ForumView> forum=DaoFactory.getInstance().getForumView_dao().query(sql);
            if (forum != null && forum.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, forum);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//新增回复
	@GET
	@Path("addTopicReply")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String addTopicReply(@QueryParam("normalAnswer") String normalAnswer)
			throws UnsupportedEncodingException {
		try {
			if(normalAnswer!=null&&!normalAnswer.equals("")){
				normalAnswer = URLDecoder.decode(normalAnswer);
				NormalAnswer answer = (NormalAnswer) CommonJson.Json2Obj(normalAnswer, NormalAnswer.class);
				if (answer != null) {
					answer.setId(IDOperation.getClassID(NormalAnswer.class.getName()));
					answer.setCreatedate(DateFormater.getTimestampByString(DateFormater.formatLongDateTime(new Date())) );
				}

				if (DaoFactory.getInstance().getNormalAnswer_dao().save(answer)) {
					return BuildResult.getResult(BuildResult.Success, answer.getId());
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "回复失败");
	}
	
	//查询所有的回复
	@GET
	@Path("queryTopicAnswer")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryTopicAnswer(@QueryParam("TopicID") String TopicID)
			throws UnsupportedEncodingException {
		try {
			String sql="select * from normal_answer_view where questionid='"+TopicID+"' ORDER BY createdate ASC";
            List<NormalAnswerView> normalAnswerView=DaoFactory.getInstance().getNormalAnswerView_dao().query(sql);
            if (normalAnswerView != null && normalAnswerView.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, normalAnswerView);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//新增话题的图片
	public String addForumImage(String forumID,String imagePath)
			throws UnsupportedEncodingException {
		try {
			  List<Forum> f=DaoFactory.getInstance().getForum_dao().findByProperty("id", forumID);
			  if(f.get(0).getPic()!=null&&!f.get(0).equals("")){
				  f.get(0).setPic(f.get(0).getPic()+","+imagePath);
			  }else{
                  f.get(0).setPic(imagePath);
			  }
				if (DaoFactory.getInstance().getForum_dao().update(f.get(0))) {
					return BuildResult.getResult(BuildResult.Success,"添加图片成功");
				}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "添加图片失败");
	}
	
	//新增话题回复的图片
	public String addReplyImage(String replyID,String imagePath)
			throws UnsupportedEncodingException {
		try {
			  List<NormalAnswer> na=DaoFactory.getInstance().getNormalAnswer_dao().findByProperty("id", replyID);
			  if(na.get(0).getAnswerPic()!=null&&!na.get(0).equals("")){
				  na.get(0).setAnswerPic(na.get(0).getAnswerPic()+","+imagePath);
			  }else{
                  na.get(0).setAnswerPic(imagePath);
			  }
				if (DaoFactory.getInstance().getNormalAnswer_dao().update(na.get(0))) {
					return BuildResult.getResult(BuildResult.Success,"添加图片成功");
				}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "添加图片失败");
	}
}
